package com.tensquare.mutual.filter;

import com.netflix.discovery.converters.Auto;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tensquare.mutual.util.MutualConstant;
import com.tensquare.util.JwtUtil;
import com.tensquare.util.NotNullHelps;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class MutualFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil ;

    private String type_before = "pre";

    // 请求前后执行 pre & post
    @Override
    public String filterType() {
        return type_before;
    }

    // 多个过滤器执行顺序 越小，越先执行
    @Override
    public int filterOrder() {
        return 0;
    }

    // 是否执行 false-不执行 true- 执行
    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 过滤器真正执行的操作, return 任何 object 的值都表示继续执行
    // 不再执行 -- setSendZuulResponse(false)
    @Override
    public Object run() throws ZuulException {
        System.out.println("@@ MutualFilter-zuul过滤器... \n");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        // 分发时，就是两个连续请求 ，第一次路径请求，第二次路由分发 ，所以第一次应该放行
        if (request.getMethod().equals("OPTIONS")) {
            log.info("$$ zuul路径请求 @@");
            return null ;
        }

        log.info("$$ zuul请求开始分发 @@");
        String requestURL = request.getRequestURL().toString();
        if (requestURL.indexOf("/admin/login")>0) {
            log.info("%% #### 登录放行 --- @@ \n\n");
            log.debug(" ## 登录页 ： " + requestURL);
            return null;
        }
        String header = request.getHeader(MutualConstant.request_header);
        if (NotNullHelps.isNotNull(header)) {
            if (header.startsWith(MutualConstant.request_header_start)) {
                String token = header.substring(7);
                try {
                    // 判断过滤头信息，转发并放行
                    Claims claims = jwtUtil.parseJWT(token);
                    String role = (String) claims.get("roles");
                    if (role.equals(MutualConstant.role_admin) == true) {
                        currentContext.addZuulRequestHeader(MutualConstant.request_header, token);
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    currentContext.setSendZuulResponse(false);
                }
            }
        }
        currentContext.setSendZuulResponse(false); // 终止运行
        currentContext.setResponseStatusCode(403);
        currentContext.setResponseBody("权限不足");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
